import NProgress from 'nprogress';
import router from '@/router';
import store from '@/store';
import {
	GET_USER,
	GET_MENU,
	MENU_ACTION,
	REQ_CANCEL_ACTION
} from '@/utils/Const';

NProgress.inc(0.2);
NProgress.configure({ easing : 'ease', speed : 500, showSpinner : false });
const whiteList = ['/login'];
router.beforeEach(async (to, from, next) => {
	NProgress.start();
	document.title = (to.meta && to.meta.title) || '核心系统';
	store.dispatch(`reqCancel/${REQ_CANCEL_ACTION}`);
	// 白名单放行
	if (whiteList.some((v) => v === to.path)) {
		next();
	} else if (!store.getters[`user/${GET_USER}`].accessToken) {
		//未登录
		NProgress.done();
		next(`/login?redirect=${to.path}`);
	} else {
		// 动态加载路由
		if (store.getters[`menu/${GET_MENU}`].length === 0) {
			const accessRoutes = await store.dispatch(`menu/${MENU_ACTION}`);
			accessRoutes.forEach((item) => {
				router.addRoute(item);
			});
			router.addRoute({
				path : '/:pathMatch(.*)*',
				hidden : true,
				redirect : '/dashboard'
			});
			next({ ...to });
		} else {
			next();
		}
	}
});

router.afterEach(() => {
	NProgress.done();
});
